package com.spaceobj.chess.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spaceobj.chess.common.Result;
import com.spaceobj.chess.entity.Replay;
import com.spaceobj.chess.service.ReplayService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

@Tag(name = "对局回放管理", description = "对局回放相关接口")
@RestController
@RequestMapping("/api/replays")
@RequiredArgsConstructor
public class ReplayController {

    private final ReplayService replayService;

    @Operation(summary = "创建对局回放")
    @PostMapping
    public Result<Replay> createReplay(@RequestBody Replay replay) {
        replayService.save(replay);
        return Result.success(replay);
    }

    @Operation(summary = "更新对局回放")
    @PutMapping("/{id}")
    public Result<Replay> updateReplay(
            @Parameter(description = "回放ID") @PathVariable Integer id,
            @RequestBody Replay replay) {
        replay.setGameId(id);
        replayService.updateById(replay);
        return Result.success(replay);
    }

    @Operation(summary = "删除对局回放")
    @DeleteMapping("/{id}")
    public Result<Void> deleteReplay(@Parameter(description = "回放ID") @PathVariable Integer id) {
        replayService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "获取回放详情")
    @GetMapping("/{id}")
    public Result<Replay> getReplay(@Parameter(description = "回放ID") @PathVariable Integer id) {
        return Result.success(replayService.getById(id));
    }

    @Operation(summary = "分页查询对局回放")
    @GetMapping
    public Result<Page<Replay>> listReplays(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "对局ID") @RequestParam(required = false) Integer gameId) {
        Page<Replay> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Replay> queryWrapper = new LambdaQueryWrapper<>();
        if (gameId != null) {
            queryWrapper.eq(Replay::getGameId, gameId);
        }
        return Result.success(replayService.page(pageParam, queryWrapper));
    }
} 